package com.twoGroup.boot.controller;

import com.alibaba.fastjson.JSONObject;
import com.twoGroup.boot.pojo.ResultDate;
import com.twoGroup.boot.pojo.User;
import com.twoGroup.boot.service.UserService;
import com.twoGroup.boot.utils.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.mail.EmailException;
import org.apache.commons.mail.SimpleEmail;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

//import com.twoGroup.boot.utils.DESUtils;

@Controller
@RequestMapping("/User")
@Api(tags = "用户接口")
public class UserController {
    public static Logger logger = LoggerFactory.getLogger(UserController.class);
    @Resource
    private UserService userService;
    private UserUtils userUtils = new UserUtils();
    private SendEmail sendEmail = new SendEmail();
    private TeleNumUtils teleNumUtils = new TeleNumUtils();
    private IdNumberUtils idNumberUtils = new IdNumberUtils();

    /**
     * 获取邮箱验证
     * @param email 邮箱
     */
    @ApiOperation(value = "发送邮箱验证码", notes = "输入邮箱")
    @PostMapping("/sendAuthCodeEmail")
    @ResponseBody
    public Object sendAuthCodeEmail(HttpServletRequest request, String email){
        HttpSession session = request.getSession();
        try {
            SimpleEmail mail = new SimpleEmail();
            mail.setHostName("smtp.qq.com");//发送邮件的服务器
            mail.setAuthentication("2385804356@qq.com","dyelqjkeazendjbf");//刚刚记录的授权码，是开启SMTP的密码
            mail.setFrom("2385804356@qq.com","twoGroup.boot客服");  //发送邮件的邮箱和发件人
            mail.setSSLOnConnect(true); //使用安全链接
            logger.info("email------>"+email);
            mail.addTo(email);//接收的邮箱
            mail.setSubject("注册验证码");//设置邮件的主题

            session.setAttribute(email,sendEmail.achieveCode());
            session.setMaxInactiveInterval(60);  //session域的存活时间为60s
            mail.setMsg("尊敬的用户:你好!\n twoGroup.boot注册验证码为:" +session.getAttribute(email)+ "\n"+"请勿将验证码透露给他人，如非本人操作，请立即访问www.baidu.com 查询 (有效期为一分钟)");//设置邮件的内容
            logger.info("emailFlag--------->"+session.getAttribute(email));
            mail.send();//发送

        } catch (EmailException e) {
            e.printStackTrace();
        }
        return session.getAttribute(email);
    }

    /**
     * 注册
     * @param model  model
     * @param password  密码
     * @param email  邮箱
     * @param nickname  昵称
     * @param request 请求
     *  页面
     */
    @ApiOperation(value = "用户注册", notes = "根据user创建用户对象")
    @PostMapping("/addUser")     //测试完成
    @ResponseBody
    public void addUser(Model model, HttpServletRequest request, String password, String email, String nickname, String code){
//        logger.info("123456789");
        boolean nicknameBool = userUtils.UserStringBool(nickname, 1, 6);
        boolean emailFlag = userUtils.EmailStringBool(email, 6, 18);
        boolean passwordFlag = userUtils.UserStringBool(password, 6, 16);
        try {
            if (passwordFlag && emailFlag && nicknameBool) {
                    if(code!=null && code.equals(request.getSession().getAttribute(email))){
                        int i = userService.addUser(password, email, nickname);
                        model.addAttribute("users",userService.queryUserToEmail(email));  //封装对象到前台
                        logger.info("注册成功");
                    }else{
                        logger.info("注册失败，验证码错误");
                    }
            } else {
                logger.info("注册失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 登录
     * @param email 邮箱
     * @param password 密码
     * @param request 请求
     */
    @ApiOperation(value = "用户登录", notes = "根据账号密码查询")
    @PostMapping("/loginUser")  //测试完成
    @ResponseBody
    public void loginUser(String email, String password, HttpServletRequest request, HttpServletResponse response) {
        boolean b = userUtils.UserStringBool(email, 6, 18);
        boolean email1 = userUtils.EmailStringBool(email,6,18);
        boolean b1 = userUtils.UserStringBool(password, 6, 16);
        Integer i = userService.selectCountEmail(email);
        try {
            if ((b && b1 && email1) && i != 0) {  //长度合法且查询可以到结果
                List<User> users = userService.loginUser(email);
                if (users.get(0).getEmail().equals(email) && users.get(0).getPassword().equals(password)) {
                    //免用户名密码登录：
                    Cookie cookieEmail = new Cookie("email", email);
                    cookieEmail.setMaxAge(60 * 60 * 24 * 7);//设置保存时间为7天

                    Cookie cookiePassword = new Cookie("password", UserUtils.md5(password));
                    cookiePassword.setMaxAge(60 * 60 * 24 * 7);//设置保存时间为7天
                    cookieEmail.setPath("/");
                    cookiePassword.setPath("/");
                    response.addCookie(cookieEmail);
                    response.addCookie(cookiePassword);

                    Integer flag = userService.booleanAdmin(email);
                    if (flag != 2) {
                        User user = userService.queryUser(email); //返回对象存入前台
                        logger.info("user--------------->"+user);
                        request.getSession().setAttribute("user",user);
                        logger.info(request.getSession().getId());
//                        logger.info(request.getSession().getAttribute("user"));
                        logger.info("用户登录登录成功：loginUser-->" + user);


                    }else {
                        User user = userService.queryUser(email); //返回对象存入前台
                        logger.info("user--------------->"+user);
                        request.getSession().setAttribute("user",user);
                        logger.info("管理员登录成功");

                    }
                }else{
                    logger.info("用户名或密码错误");

                }
            }else{
                logger.info("长度不合法或用户不存在");

            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * 退出登录
     * @param request d
     */
    @ApiOperation(value = "退出登录", notes = "点击退出登录")
    @PostMapping("/loginOut")  //测试完成
    public String loginOut(HttpServletRequest request , HttpServletResponse response){
        Cookie cookieEmail = new Cookie("email", "");
        Cookie cookiePassword = new Cookie("password", "");
        cookieEmail.setPath("/");
        cookiePassword.setPath("/");
        response.addCookie(cookieEmail);
        response.addCookie(cookiePassword);
        request.getSession().invalidate();
        System.out.println("/loginOut调用成功");
        return "redirect:/";
    }

    /**
     * 重置密码
     * @param model model
     * @param newEmail 邮箱
     * @param newPassword 新密码
     */
    @ApiOperation(value = "重置密码", notes = "邮箱发送验证码")
    @PostMapping("/resetPassword")  //测试完成
    @ResponseBody
    public int resetPassword(Model model, HttpServletRequest request, String newEmail , String newPassword, String newCode)throws ServletException, IOException {
        boolean c = userUtils.UserStringBool(newEmail, 6, 18);
        boolean b = userUtils.UserStringBool(newPassword, 6, 16);
        Integer integer = userService.selectCountEmail(newEmail);
        try {
            if(integer!=0&&b){
                if(newCode != null && newCode.equals(request.getSession().getAttribute(newEmail))){
                    logger.info("重置密码成功");
                    return userService.resetPassword(newEmail, newPassword);
                }else{
                    logger.info("验证码错误");
                }
            }else{
                logger.info("失败,账号不存在或账号密码长度不合法");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }

    /**
     * 用户注销
     * @param id 传入用户id
     * @return 注销
     */
    @ApiOperation(value = "账号注销", notes = "根据id值")
    @PostMapping("/deleteUser") //测试完成
    public String deleteUser(Integer id) {
        int i = userService.deleteUser(id);
        return "/pages/pagesFel/index";  //返回主页
    }

    /**
     * 查询用户信息
     *
     * @param userId 传入用户id
     * @return list集合
     */
    @ApiOperation(value = "根据id查询用户信息", notes = "通过id")
    @PostMapping("/queryUserId") //测试完成
    @ResponseBody
    public User queryUserId(Integer userId) {
        return userService.selectUserId(userId);
    }


    @ApiOperation(value = "用户修改个人信息", notes = "直接修改")
    @PostMapping("/updateUser")  //测试完成
    @ResponseBody
    public String updateUser(User user) {
             int i = userService.updateUser(user);
             if (i == 1) {
                 logger.info("修改成功");
                 return "修改成功";
             } else {
                 logger.info("修改失败 i==0");
                 return "修改失败";
             }
    }

    /**
     * 用户申请成为商家
     * @param userId 传入用户id
     * @return 返回
     */
    @ApiOperation(value = "用户申请为商家", notes = "通过id")
    @PostMapping("/applyBusiness") //测试完成
    @ResponseBody
    public int applyBusiness(Integer userId) {
        return userService.applyBusiness(userId);
    }

    /**
     * 修改密码
     * @param userId 用户id
     * @param password 密码
     */
    @ApiOperation(value = "修改密码", notes = "传入用户id，password 原密码不正确返回0 修改成功返回1 原密码 新密码长度不够返回2")
    @PostMapping("/updatePassword")
    @ResponseBody
    public int updatePassword(Integer userId, String password, String newpassword){
        return userService.updatePassword(userId, password, newpassword);
    }

    @ApiOperation(value = "修改头像", notes = "传入图片")
    @ResponseBody
    @PostMapping("/uploadUserImg")
    public ResultDate updateUserHeadImg(@RequestParam MultipartFile image, HttpSession session){
        if(image.isEmpty()){
            return ResultDate.fail("文件为空，请重新上传！");
        }
        String Orignalfilename = image.getOriginalFilename();
        logger.info(Orignalfilename);
        if(Orignalfilename.endsWith(".jpg")||Orignalfilename.endsWith(".png")||Orignalfilename.endsWith(".jpeg")||Orignalfilename.endsWith("webp")) {
            User user =(User) session.getAttribute("user");
            QiniuCloudUtil qiniuCloudUtil=new QiniuCloudUtil();
            try {
                byte[] bytes=image.getBytes();
                String imageName= UUID.randomUUID().toString();
                imageName="http://"+qiniuCloudUtil.put64image(bytes,imageName);
                if(userService.updateHeadImg(user.getUserId(),imageName)==1){
                    return  ResultDate.success("文件上传成功！");
                }else{
                    return ResultDate.fail("文件上传失败！");
                }
            } catch (IOException e) {
                return ResultDate.fail("文件上传失败！");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return ResultDate.fail("文件格式有误！");
    }


    @ApiOperation(value = "getEmailFlag", notes = "判断该邮箱是否存在")
    @GetMapping("/getEmailFlag")     //测试完成
    @ResponseBody
    public String getEmailFlag(String email, HttpServletRequest request){
        Integer emailFlag = userService.selectCountEmail(email);
        logger.info(String.valueOf(emailFlag));
        request.getSession().setAttribute("emailFlag",emailFlag);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("emailFlag", request.getSession().getAttribute("emailFlag"));
        return JSONObject.toJSONString(jsonObject);
    }

//    @ApiOperation(value = "getNicknameFlag", notes = "判断该用昵称是否存在")
//    @GetMapping("/getNicknameFlag")     //测试完成
//    @ResponseBody
//    public String getNicknameFlag(String nickname, HttpServletRequest request){
//        Integer nicknameFlag = userService.queryNickname(nickname);
//        logger.info(nicknameFlag);
//        request.getSession().setAttribute("nicknameFlag",nicknameFlag);
//        JSONObject jsonObject = new JSONObject();
//        jsonObject.put("nicknameFlag", request.getSession().getAttribute("nicknameFlag"));
//        return JSONObject.toJSONString(jsonObject);
//    }

    @ApiOperation(value = "flag", notes = "返回值 flag 查看用户的身份")
    @PostMapping("/getFlag")
    @ResponseBody
    public String getFlag(HttpServletRequest request, String email){
        Integer flag = userService.booleanAdmin(email);
        logger.info(String.valueOf(flag));
        request.getSession().setAttribute("flag",flag);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("flag", request.getSession().getAttribute("flag"));
        return JSONObject.toJSONString(jsonObject);
    }

    @ApiOperation(value = "password", notes = "返回值 password 获取该邮箱的密码")
    @PostMapping("/getPassword")
    @ResponseBody
    public String getPassword(HttpServletRequest request, String email){
//        List<User> users = userService.loginUser(email);
        User user = userService.queryUser(email);
        logger.info("------------>2"+user.getPassword());
        request.getSession().setAttribute("password",user.getPassword());
//        logger.info(request.getSession().getAttribute("password"));
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("password", request.getSession().getAttribute("password"));
        return JSONObject.toJSONString(jsonObject);
    }

    @ApiOperation(value = "getEmailCard", notes = "获取邮箱验证码")
    @PostMapping("/getEmailCard")
    @ResponseBody
    public String getEmailCard(HttpServletRequest request, String email){
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("email", request.getSession().getAttribute(email));
        logger.info("===================1"+email);
        return JSONObject.toJSONString(jsonObject);
    }
}
